{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: Symmetry-reduced Pulse Design Tool (MAST-U-like)\n", "\n", "---\n", "\n", "This notebook demonstrates how to use `SymmetryReducedSolver` with the **FreeGSNKE Pulse Design Tool** (FPDT) on a MAST-U-like tokamak, evolving the coupled plasma/metal system strictly in the even-in-$Z$ subspace. It repeats the closed-loop simulation of Example 12b on the MAST-U-like machine with the plasma-control-system (PCS) settings of Example 11, and adds a feedback-controlled sweep of the lower outer divertor strikepoint radius from a conventional position ($R_{\\mathrm{sp}} \\approx 0.74\\text{ m}$) out to a Super-X configuration ($R_{\\mathrm{sp}} = 1.40\\text{ m}$).\n", "\n", "This enables large timesteps to be taken ($5\\times$ larger than the $0.5\\text{ ms}$ timestep used in Example 11) for rapid prototyping of plasma scenarios.\n", "\n", "In this notebook, we:\n", "1. Prepare an exactly up-down symmetric version of the MAST-U-like machine.\n", "2. Construct a symmetric initial Grad-Shafranov equilibrium.\n", "3. Build the virtual circuits for the PCS (including the lower outer strikepoint radius) and configure it with the settings of Example 11.\n", "4. Inspect the even and odd passive structure modes.\n", "5. Run a closed-loop FPDT simulation using `SymmetryReducedSolver` in place of `nl_solver`.\n", "\n", "**Note:** the MAST-U-like machine is only approximately up-down symmetric, so symmetrising it changes the machine slightly. The vertical-control circuit `P6` is electrically odd and is removed in the process, so this simulation has no active vertical control: the plasma is held on the midplane by the symmetry itself, and the vertical instability cannot be studied (see Example 11 for that)." ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### 1. Build the symmetrised MAST-U-like machine\n", "\n", "We load the same MAST-U-like description as Example 11 and use `prepare_up_down_symmetric_machine` (see Example 12a) to turn it into an exactly up-down symmetric one. Three things are worth noting:\n", "\n", "- The active coils are series-connected upper/lower pairs, so each is already a single even circuit. The exception is `P6`, whose lower bundle has the opposite polarity: it is electrically odd, so we exclude it explicitly (`exclude_odd_active=True`).\n", "- The upper and lower passive structures, limiter, and wall agree only to a few millimetres, with a small common vertical offset. With `z_midplane=\"auto\"` the offset is fitted and removed, and the paired elements are then averaged. Pairs are found automatically from their names and reflected geometry.\n", "- The limiter and wall are intersected with their reflections, which removes a small area (below 0.3%) from each." ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import pickle\n", "import time\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "from freegsnke import GSstaticsolver, build_machine, equilibrium_update\n", "from freegsnke.jtor_update import Lao85\n", "from freegsnke.up_down_symmetry import prepare_up_down_symmetric_machine" ] }, { "cell_type": "code", "execution_count": null, "id": "3", "metadata": {}, "outputs": [], "source": [ "# load the (approximately symmetric) MAST-U-like machine description used in Example 11\n", "machine_path = \"../machine_configs/MAST-U/MAST-U_like_\"\n", "machine_data = {}\n", "for part in (\"active_coils\", \"passive_coils\", \"limiter\", \"wall\"):\n", " with open(f\"{machine_path}{part}.pickle\", \"rb\") as file:\n", " machine_data[part] = pickle.load(file)\n", "\n", "# exactly up-down symmetric machine data (the odd circuit P6 is excluded)\n", "symmetric_machine = prepare_up_down_symmetric_machine(\n", " machine_data[\"active_coils\"],\n", " machine_data[\"passive_coils\"],\n", " limiter_data=machine_data[\"limiter\"],\n", " wall_data=machine_data[\"wall\"],\n", " z_midplane=\"auto\",\n", " exclude_odd_active=True,\n", " verbose=True,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "# build machine\n", "tokamak = build_machine.tokamak(\n", " active_coils_data=symmetric_machine.even_active_coils_data,\n", " passive_coils_data=symmetric_machine.passive_coils_data,\n", " limiter_data=symmetric_machine.limiter_data,\n", " wall_data=symmetric_machine.wall_data,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "# plot machine (notice the P6 coils now missing, around (R,Z)=(1.25, +/-1.1))\n", "fig, ax = plt.subplots(figsize=(4, 8), dpi=80)\n", "tokamak.plot(axis=ax, show=False)\n", "ax.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "ax.set(xlabel=\"Major radius, R [m]\", ylabel=\"Height, Z [m]\", aspect=\"equal\")\n", "ax.grid(zorder=0, alpha=0.75)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "6", "metadata": {}, "source": [ "### 2. Construct a symmetric initial equilibrium\n", "\n", "Symmetrising the machine changes it slightly, so the initial equilibrium of Example 11 must be solved again on the new machine. The upper and lower coils of every retained circuit are in series, so the circuit currents of Example 11 (and hence the PCS current limits defined for them) apply unchanged, and we simply repeat its forward solve with the same currents and plasma profiles, forcing the solution to be even in $Z$. (An inverse solve would also work, but would need new shape constraints and would give different coil currents.) The tiny current in `P6` is dropped with the circuit." ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "# initialise eq (same grid as Example 11)\n", "eq = equilibrium_update.Equilibrium(\n", " tokamak=tokamak,\n", " Rmin=0.1,\n", " Rmax=2.0,\n", " Zmin=-2.2,\n", " Zmax=2.2,\n", " nx=65,\n", " ny=65,\n", ")\n", "\n", "# initialise profiles (same as Example 11)\n", "profiles = Lao85(\n", " eq=eq,\n", " Ip=7.59e5,\n", " fvac=-0.52,\n", " alpha=[362685, 17696],\n", " beta=[0.103, 0.753],\n", " alpha_logic=True,\n", " beta_logic=True,\n", ")\n", "\n", "# initial coil currents (same as Example 11; the passive structures start with no current)\n", "coil_currents = np.array(\n", " [\n", " 2766.10782056, 193.12768191, 4019.86873871, 4857.42357466,\n", " -726.99282376, -1696.92521166, -77.7252396, 266.38207493,\n", " -73.01483716, -4169.86874271, -4518.28147417,\n", " ]\n", ")\n", "active_coils = list(tokamak.coils_list[: tokamak.n_active_coils])\n", "for name, current in zip(active_coils, coil_currents):\n", " tokamak.set_coil_current(coil_label=name, current_value=current)\n", "\n", "# static solver\n", "static_solver = GSstaticsolver.NKGSsolver(eq)" ] }, { "cell_type": "code", "execution_count": null, "id": "8", "metadata": {}, "outputs": [], "source": [ "# the numerical operators need exactly up-down symmetric resistances and inductances, so these calls enforce this\n", "eq._vgreen = symmetric_machine.symmetrise_even_machine_greens(eq._vgreen)\n", "tokamak.coil_resist = symmetric_machine.symmetrise_even_machine_resistances(\n", " tokamak.coil_resist\n", ")\n", "tokamak.coil_self_ind = symmetric_machine.symmetrise_even_machine_square_operator(\n", " tokamak.coil_self_ind\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "# solve for the equilibrium (even in Z)\n", "static_solver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " constrain=None,\n", " target_relative_tolerance=1e-8,\n", " force_up_down_symmetric=True,\n", " verbose=False,\n", ")" ] }, { "cell_type": "markdown", "id": "10", "metadata": {}, "source": [ "We should have a nice up-down symmetric, diverted equilibrium in the symmetric machine, with the same X-point radius, inner/outer radii, and coil currents as Example 11." ] }, { "cell_type": "code", "execution_count": null, "id": "11", "metadata": {}, "outputs": [], "source": [ "# plot the equilibrium\n", "fig1, ax1 = plt.subplots(1, 1, figsize=(4, 8), dpi=80)\n", "ax1.grid(zorder=0, alpha=0.75)\n", "ax1.set_aspect(\"equal\")\n", "eq.tokamak.plot(axis=ax1, show=False) # plots the active coils and passive structures\n", "ax1.fill(tokamak.wall.R, tokamak.wall.Z, color=\"k\", linewidth=1.2, facecolor=\"w\", zorder=0) # plots the limiter\n", "eq.plot(axis=ax1, show=False) # plots the equilibrium\n", "ax1.set_xlim(0.1, 2.15)\n", "ax1.set_ylim(-2.25, 2.25)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "12", "metadata": {}, "source": [ "If needed we can do some checks to ensure everything is fully up-down symmetric (i.e. machine operators commute with the metal-current reflection, the limiter mask is reflection-invariant, and the initial plasma fields and metal currents are even to round-off)." ] }, { "cell_type": "code", "execution_count": null, "id": "13", "metadata": {}, "outputs": [], "source": [ "passive_reflection_operator = symmetric_machine.passive_reflection_operator\n", "reflection_operator = symmetric_machine.even_machine_reflection_operator\n", "\n", "\n", "def relative_reflection_error(values, parity=1):\n", " denominator = np.linalg.norm(values)\n", " if denominator == 0:\n", " return 0.0\n", " return np.linalg.norm(values - parity * values[:, ::-1]) / denominator\n", "\n", "\n", "def relative_commutator_error(matrix):\n", " numerator = np.linalg.norm(\n", " reflection_operator @ matrix - matrix @ reflection_operator\n", " )\n", " return numerator / np.linalg.norm(matrix)\n", "\n", "\n", "reflected_greens = np.einsum(\n", " \"ij,jrz->irz\", reflection_operator, eq._vgreen[:, :, ::-1]\n", ")\n", "resistance_matrix = np.diag(tokamak.coil_resist)\n", "initial_currents = tokamak.getCurrentsVec()\n", "symmetry_errors = {\n", " \"sampled Green functions\": (\n", " np.linalg.norm(eq._vgreen - reflected_greens)\n", " / np.linalg.norm(eq._vgreen)\n", " ),\n", " \"inductance operator\": relative_commutator_error(tokamak.coil_self_ind),\n", " \"resistance operator\": relative_commutator_error(resistance_matrix),\n", " \"plasma flux\": relative_reflection_error(eq.plasma_psi),\n", " \"toroidal current density\": relative_reflection_error(profiles.jtor),\n", " \"metal currents\": (\n", " np.linalg.norm(reflection_operator @ initial_currents - initial_currents)\n", " / np.linalg.norm(initial_currents)\n", " ),\n", "}\n", "limiter_defects = np.count_nonzero(\n", " eq.limiter_handler.mask_inside_limiter\n", " != eq.limiter_handler.mask_inside_limiter[:, ::-1]\n", ")\n", "\n", "for name, error in symmetry_errors.items():\n", " print(f\"{name:27s}: {error:.3e}\")\n", "print(f\"{'limiter-mask defects':27s}: {limiter_defects}\")\n", "assert max(symmetry_errors.values()) < 1e-12\n", "assert limiter_defects == 0" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "### 3. Build the virtual circuits for the PCS\n", "\n", "We use FreeGSNKE's `VirtualCircuitHandling` class (see Example 09) to build the virtual circuits (VCs) for the ten shaping circuits (all circuits except the solenoid). It computes, by finite differences of static GS solves, the shape sensitivity matrix\n", "\n", "$$\n", "S_{kj} = \\frac{\\partial s_k}{\\partial I_j},\n", "$$\n", "\n", "where $s_k$ are the shape targets (`Rin`, `Rout`, `Rx`, `Zx`, `Rsp`, defined below) and $I_j$ the shaping-circuit currents, and its pseudo-inverse $S^+$ (the VCs), which maps requested shape corrections to coil-current commands. The solenoid is excluded because it is reserved for plasma-current control.\n", "\n", "In addition to the four shape targets of Example 11 (`Rin`, `Rout`, `Rx`, `Zx`), we include the radial position of the lower outer divertor strikepoint, `Rsp`. To extract it from an equilibrium object, `lower_outer_strikepoint(equilibrium)` calls `equilibrium.strikepoints()`, which returns the $(R, Z)$ intersections of the $\\psi_{\\mathrm{boundary}}$ contour with `tokamak.wall`. For a symmetric double-null diverted plasma this returns four points (inner and outer strikepoints in the lower and upper divertors); filtering to the lower divertor ($Z < 0$) and taking the point with largest $R$ selects the lower outer divertor tile intersection." ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "def lower_outer_strikepoint(equilibrium):\n", " \"\"\"Return the (R, Z) coordinates of the lower outer divertor strikepoint.\"\"\"\n", " strikes = np.atleast_2d(equilibrium.strikepoints())\n", " lower_strikes = strikes[strikes[:, 1] < 0.0]\n", " return lower_strikes[np.argmax(lower_strikes[:, 0])]\n", "\n", "\n", "# functions for the plasma descriptors (shape functions), extending Example 11 with Rsp\n", "def plasma_descriptors(equilibrium):\n", " \"\"\"Return the five shape measurements used by the controller: Rin, Rout, Rx, Zx, Rsp.\"\"\"\n", " # inboard/outboard midplane radii\n", " rin_rout = equilibrium.innerOuterSeparatrix()\n", "\n", " # find the lower X-point: define a \"box\" in which to search for it\n", " xpt_box = [[0.33, -0.88], [0.95, -1.38]]\n", " xpt_mask = (\n", " (equilibrium.xpt[:, 0] >= xpt_box[0][0])\n", " & (equilibrium.xpt[:, 0] <= xpt_box[1][0])\n", " & (equilibrium.xpt[:, 1] <= xpt_box[0][1])\n", " & (equilibrium.xpt[:, 1] >= xpt_box[1][1])\n", " )\n", " xpts = equilibrium.xpt[xpt_mask, 0:2].reshape(-1, 2)\n", " # if there is more than one candidate, take the one closest to the O-point\n", " nearest = np.argmin(np.linalg.norm(xpts - equilibrium.opt[0, 0:2], axis=1))\n", " rx, zx = xpts[nearest]\n", "\n", " # lower outer divertor strikepoint radius\n", " rsp, _ = lower_outer_strikepoint(equilibrium)\n", "\n", " return np.array([rin_rout[0], rin_rout[1], rx, zx, rsp])\n", "\n", "\n", "# names of the shape targets\n", "ctrl_targets = [\"Rin\", \"Rout\", \"Rx\", \"Zx\", \"Rsp\"]\n", "\n", "# calculate initial values\n", "baseline_descriptors = plasma_descriptors(eq)\n", "\n", "print(\"Active circuit order:\", active_coils)\n", "print(\"Shape parameters:\", ctrl_targets)\n", "print(\"Initial descriptors [m]:\", baseline_descriptors)" ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "from freegsnke import virtual_circuits\n", "\n", "# build the VCs (all shape targets are included in the calculation, the solenoid is excluded)\n", "shape_coils = active_coils[1:]\n", "VCs = virtual_circuits.VirtualCircuitHandling()\n", "VCs.define_solver(static_solver)\n", "VCs.calculate_VC(\n", " eq=eq,\n", " profiles=profiles,\n", " coils=shape_coils,\n", " target_names=ctrl_targets,\n", " target_calculator=plasma_descriptors,\n", " n_vc_workers=2,\n", " verbose=True,\n", " name=\"VC_shape\",\n", ")\n", "\n", "shape_matrix = VCs.VC_shape.shape_matrix # [no. of targets x no. of coils], units m/A\n", "shape_vcs = VCs.VC_shape.VCs_matrix # [no. of coils x no. of targets], units A/m" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "### 4. Configure the plasma-control loop\n", "\n", "Here we set up the FPDT controllers as in Example 11 (with the same references, gains, limits, and time window), adding feedback control of the lower outer strikepoint radius `Rsp`, and omitting the vertical-control circuit. The controllers:\n", "\n", "- hold the plasma current at its initial value ($7.59 \\times 10^5\\text{ A}$), counteracting its resistive decay;\n", "- hold `Rin` and `Rout` at $0.28\\text{ m}$ and $1.35\\text{ m}$;\n", "- ramp the lower X-point radius, $R_x$, from $0.57\\text{ m}$ inwards to $0.50\\text{ m}$ and back again;\n", "- leave the lower X-point height, $Z_x$, uncontrolled (its blend is zero, so its virtual circuit is set to zero, as in Example 11);\n", "- hold the lower outer strikepoint radius, $R_{\\mathrm{sp}}$, at its initial value ($0.74\\text{ m}$) for $50\\text{ ms}$, sweep it linearly over $150\\text{ ms}$ out to a Super-X position at $1.40\\text{ m}$ ($t = 200\\text{ ms}$), and hold it there for the remainder of the simulation.\n", "\n", "The shape controllers use proportional-only control (`k_int` = 0), as in Example 11. Note that the equilibrium starts a few millimetres away from the `Rin`, `Rout`, and `Rx` references." ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [ "from freegsnke.control_loop.pcs import PlasmaControlSystem\n", "\n", "# simulation window (as in Example 11)\n", "tmin = 0.0\n", "tmax = 0.25\n", "n_active = tokamak.n_active_coils\n", "zeros = {\"times\": np.array([tmin, tmax]), \"vals\": np.zeros(2)}\n", "\n", "# PLASMA CATEGORY (as in Example 11): hold Ip at its initial value with PID feedback only\n", "plasma_data = {\n", " \"ip_ref\": {\"times\": np.array([tmin, tmax]), \"vals\": np.full(2, profiles.Ip)},\n", " \"vloop_ff\": zeros,\n", " \"ip_blend\": {\"times\": np.array([tmin, tmax]), \"vals\": np.ones(2)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([-5 * 4])},\n", " \"k_int\": {\"times\": np.array([tmin]), \"vals\": np.array([-50 * 2])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0])},\n", " \"M_solenoid\": {\"times\": np.array([tmin]), \"vals\": np.array([1.0])},\n", "}\n", "\n", "\n", "# SHAPE CATEGORY (as in Example 11, plus Rsp sweep to Super-X)\n", "def shape_waveforms(ref_times, ref_values, k_prop, blend=1.0):\n", " \"\"\"Return the waveforms of one shape target (a proportional-only controller).\"\"\"\n", " return {\n", " \"ff\": zeros,\n", " \"ref\": {\"times\": np.array(ref_times), \"vals\": np.array(ref_values)},\n", " \"blend\": {\"times\": np.array([tmin, tmax]), \"vals\": np.full(2, blend)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([k_prop])},\n", " \"k_int\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " }\n", "\n", "\n", "rsp_initial = np.round(baseline_descriptors[ctrl_targets.index(\"Rsp\")], 2)\n", "shape_data = {\n", " \"Rin\": shape_waveforms([tmin, tmax], [0.28, 0.28], 120),\n", " \"Rout\": shape_waveforms([tmin, tmax], [1.35, 1.35], 170),\n", " \"Rx\": shape_waveforms(\n", " [tmin, 0.025, 0.075, 0.175, 0.225, tmax],\n", " [0.57, 0.57, 0.5, 0.5, 0.57, 0.57],\n", " 120,\n", " ),\n", " \"Zx\": shape_waveforms([tmin, tmax], [-1.24, -1.24], 120, blend=0.0), # uncontrolled\n", " \"Rsp\": shape_waveforms(\n", " [tmin, 0.05, 0.20, tmax],\n", " [rsp_initial, rsp_initial, 1.40, 1.40],\n", " 120,\n", " ),\n", "}" ] }, { "cell_type": "markdown", "id": "19", "metadata": {}, "source": [ "### Virtual circuits and electrical limits\n", "\n", "The shape virtual circuits are the columns of $S^+$ (padded with zero on the solenoid), while the plasma-current virtual circuit acts solely on the solenoid. As in Example 11, the `Zx` virtual circuit is zero. The PCS current and voltage limits are copied from Example 11 (the same eleven circuits in the same order), including its limits that keep the `P4` and `P5` currents negative. Resistances and inductances are taken directly from the symmetrised tokamak object." ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "# VIRTUAL CIRCUITS CATEGORY\n", "circuits_data = {\"coil_order\": active_coils}\n", "for target_index, target in enumerate(ctrl_targets):\n", " circuit = np.zeros(n_active)\n", " if target != \"Zx\": # Zx is not controlled\n", " circuit[1:] = shape_vcs[:, target_index]\n", " circuits_data[target] = {\"times\": np.array([tmin]), \"vals\": [circuit]}\n", "circuits_data[\"plasma\"] = {\n", " \"times\": np.array([tmin]),\n", " \"vals\": [np.r_[1.0, np.zeros(n_active - 1)]],\n", "}\n", "for coil_name in active_coils: # no feedforward coil-current drives\n", " circuits_data[f\"{coil_name}_ref\"] = zeros\n", "\n", "# SYSTEMS CATEGORY (limits as in Example 11)\n", "initial_active = tokamak.getCurrentsVec()[:n_active]\n", "min_current_lims = np.array([-10000, -7000, -9000, -9000, -9000, -9000, -9000, -9000, -9000, -10000, -10000], dtype=float)\n", "max_current_lims = np.array([10000, 7000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 0, 0], dtype=float)\n", "systems_data = {\n", " \"min_coil_curr_lims\": {\"times\": [tmin], \"vals\": [min_current_lims]},\n", " \"max_coil_curr_lims\": {\"times\": [tmin], \"vals\": [max_current_lims]},\n", " \"max_coil_curr_ramp_lims\": {\"times\": [tmin], \"vals\": [1e12 * np.ones(n_active)]},\n", "}\n", "for coil_name in active_coils:\n", " systems_data[f\"{coil_name}_pert\"] = zeros\n", "\n", "# PF CATEGORY (gains and voltage limits as in Example 11)\n", "voltage_lims = np.array([2000.0] + [750.0] * (n_active - 1))\n", "pf_data = {\n", " \"R_matrix\": {\"times\": [tmin], \"vals\": [tokamak.coil_resist[:n_active]]},\n", " \"M_FF_matrix\": {\n", " \"times\": [tmin],\n", " \"vals\": [tokamak.coil_self_ind[:n_active, :n_active]],\n", " },\n", " \"M_FB_matrix\": {\n", " \"times\": [tmin],\n", " \"vals\": [tokamak.coil_self_ind[:n_active, :n_active]],\n", " },\n", " \"coil_gains\": {\"times\": [tmin], \"vals\": [0.015 * np.ones(n_active)]},\n", " \"coil_voltage_lims\": {\"times\": np.array([tmin]), \"vals\": [voltage_lims]},\n", " \"coil_voltage_slew_lims\": {\"times\": [tmin], \"vals\": [1e12 * np.ones(n_active)]},\n", "}\n", "\n", "# VERTICAL CATEGORY: no vertical-control circuit (P6 is odd and was excluded), so no vertical feedback\n", "vertical_data = {\n", " \"z_ref\": {\"times\": np.array([tmin, tmax]), \"vals\": np.zeros(2)},\n", " \"k_prop\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", " \"k_deriv\": {\"times\": np.array([tmin]), \"vals\": np.array([0.0])},\n", "}\n", "\n", "# COIL ACTIVATIONS CATEGORY: all coils active throughout\n", "activation_data = {\n", " f\"{name}_activation\": {\"times\": np.array([tmin]), \"vals\": np.array([1.0])}\n", " for name in active_coils\n", "}" ] }, { "cell_type": "markdown", "id": "21", "metadata": {}, "source": [ "### Assemble the PCS\n", "\n", "The standard `PCS` interface is unchanged: symmetry reduction is handled entirely by the evolutive solver." ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "# build\n", "pcs = PlasmaControlSystem(\n", " plasma_data=plasma_data,\n", " shape_data=shape_data,\n", " shape_control_mode=\"PID\",\n", " circuits_data=circuits_data,\n", " systems_data=systems_data,\n", " pf_data=pf_data,\n", " vertical_data=vertical_data,\n", " coil_activation_data=activation_data,\n", " active_coils=active_coils,\n", " ctrl_coils=active_coils,\n", " vertical_coils=[],\n", " ctrl_targets=ctrl_targets,\n", " plasma_target=[\"plasma\"],\n", ")" ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "### 5. Initialise the reduced evolutive solver\n", "\n", "In Example 10 we showed that the metals and the plasma are governed by the circuit equation (2) and the plasma equation (3). Linearising the plasma current density about the current equilibrium (equation (4)) gives the state-matrix system\n", "\n", "$$\n", "\\mathbf{M}\\dot{\\mathbf{x}} + \\mathbf{R}\\mathbf{x} = \\mathbf{c}, \\qquad \\mathbf{x} = \\begin{bmatrix} \\vec{I}_m \\\\ I_p \\end{bmatrix}, \\qquad A = -\\mathbf{R}^{-1}\\mathbf{M},\n", "$$\n", "\n", "where the eigenvalues of $A$ are the timescales $\\tau_i$ of the system ($\\tau_i > 0$ unstable, $\\tau_i < 0$ stable). The `nl_solver` used in Examples 05 and 11 evolves all of these modes (or a subset if needed). This includes the fast, vertically unstable mode, whose short timescale forces a small timestep ($0.5\\text{ ms}$ in Example 11).\n", "\n", "`SymmetryReducedSolver` removes that mode by exploiting the up-down symmetry of the machine and the equilibrium. Let $S_m$ be the reflection operator for the metal currents (it swaps each upper/lower partner) and $S_y$ the reflection of the plasma grid about $Z = 0$. For an exactly symmetric machine and equilibrium, reflected partners have equal resistances and inductances, and the Jacobians in equation (4) are even fields. The linearised system then commutes with reflection, $SA = AS$ with $S = \\mathrm{diag}(S_m, 1)$, so the even and odd parts of the state evolve independently: an even perturbation never drives an odd response. The vertical instability is a vertical displacement of the plasma, which is odd, so it lives in the odd part and is removed by keeping only the even part.\n", "\n", "#### How the passive modes are calculated\n", "\n", "The passive structures obey the circuit equation (2) with no plasma and no applied voltage:\n", "\n", "$$\n", "M_{p,p}\\dot{\\vec{I}}_p + R_{p,p}\\vec{I}_p = 0.\n", "$$\n", "\n", "We form $A_p = -R_{p,p}^{-1}M_{p,p}$ and solve the eigenproblem\n", "\n", "$$\n", "A_p\\vec{v}_i = \\tau_i\\vec{v}_i.\n", "$$\n", "\n", "Each eigenvector $\\vec{v}_i$ is a pattern of passive currents that decays as $e^{t/\\tau_i}$. All $\\tau_i$ are negative because the passive structures only dissipate energy. The modes are stored with their decay rates $1/|\\tau_i|$ and sorted from lowest rate (slowest decay) upwards.\n", "\n", "For $n=138$ passive elements, we obtain $n/2 = 69$ up-down symmetric pairs. The passive reflection operator $S_p$ is a permutation matrix, built from the pairing found by `prepare_up_down_symmetric_machine`, that swaps each upper/lower partner. For a pair $(u, l)$:\n", "\n", "- the $S_p = +1$ eigenvector is $(e_u + e_l)/\\sqrt{2}$: both partners carry the same current, giving flux that is **even** in $Z$.\n", "- the $S_p = -1$ eigenvector is $(e_u - e_l)/\\sqrt{2}$: the partners carry opposite currents, giving a field that is **odd** in $Z$. This is the kind of current that responds to vertical plasma motion.\n", "\n", "The 69 pairs therefore give a 69-dimensional even subspace and a 69-dimensional odd subspace. A passive element on the midplane has no partner and contributes to the even subspace only (there is none in this machine).\n", "\n", "We solve the eigenproblem separately in each subspace, so every mode has a definite parity, even when eigenvalues are degenerate. This requires $S_pA_p = A_pS_p$, which holds when the resistances and inductances are reflection-symmetric. The solver checks this and raises an error if it fails.\n", "\n", "#### What the reduced solver evolves\n", "\n", "We keep only (a subset of) the even modes. The metal currents are written as $\\vec{I}_m = P\\vec{\\alpha}$, where the columns of $P$ are the active-coil unit vectors and the retained even passive modes (in the following cell, we will retain 30 of the 69 even modes, chosen by their coupling to the plasma as in Example 11). The odd modes are removed before the plasma coupling is built. The reduced state is then\n", "\n", "$$\n", "\\mathbf{x}_+ = \\begin{bmatrix} \\vec{\\alpha} \\\\ I_p \\end{bmatrix} \\qquad (11 \\text{ active circuits} + 30 \\text{ passive modes} + I_p = 42 \\text{ values}).\n", "$$\n", "\n", "Substituting $\\vec{I}_m = P\\vec{\\alpha}$ into equation (5), multiplying by $P^{-1}R_{m,m}^{-1}$, and dividing equation (6) by the lumped plasma resistance $R_p$ gives the same equations as Example 10 in the reduced state:\n", "\n", "$$\n", "\\mathbf{M}_+\\dot{\\mathbf{x}}_+ + \\mathbf{x}_+ = \\mathbf{f},\n", "$$\n", "\n", "$$\n", "\\mathbf{M}_+ =\n", "\\begin{bmatrix}\n", "P^{-1}R_{m,m}^{-1}\\left( M_{m,m}P + M_{m,y}\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\alpha}} \\right) &\n", "P^{-1}R_{m,m}^{-1}M_{m,y}\\dfrac{\\partial \\vec{I}_y}{\\partial I_p} \\\\[2ex]\n", "\\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}\\left( M_{y,m}P + M_{y,y}\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\alpha}} \\right) &\n", "\\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}M_{y,y}\\dfrac{\\partial \\vec{I}_y}{\\partial I_p}\n", "\\end{bmatrix},\n", "$$\n", "\n", "$$\n", "\\mathbf{f} =\n", "\\begin{bmatrix} P^{-1}R_{m,m}^{-1}\\vec{V}_m \\\\ 0 \\end{bmatrix}\n", "-\n", "\\begin{bmatrix} P^{-1}R_{m,m}^{-1}M_{m,y} \\\\[1ex] \\dfrac{\\hat{\\vec{I}}_y^{T}}{R_p}M_{y,y} \\end{bmatrix}\n", "\\dfrac{\\partial \\vec{I}_y}{\\partial \\vec{\\theta}}\\dot{\\vec{\\theta}}.\n", "$$\n", "\n", "The Jacobians $\\partial\\vec{I}_y/\\partial\\vec{\\alpha}$, $\\partial\\vec{I}_y/\\partial I_p$ and $\\partial\\vec{I}_y/\\partial\\vec{\\theta}$ come from Grad-Shafranov solves forced to be even in $Z$, and are projected with $\\Pi_+ = \\tfrac{1}{2}(I + S_y)$ to remove odd round-off. The system is advanced with implicit Euler,\n", "\n", "$$\n", "\\mathbf{x}_+(t + \\Delta t) = (\\mathbf{M}_+ + \\Delta t\\,\\mathbf{I})^{-1}\\left(\\Delta t\\,\\mathbf{f} + \\mathbf{M}_+\\mathbf{x}_+(t)\\right).\n", "$$\n", "\n", "After each step the equilibrium is updated with a Grad-Shafranov solve, and the Jacobians are rebuilt if the plasma current density has changed by more than the relinearisation threshold.\n", "\n", "**Note:** Without the odd modes, the fastest remaining timescales are resistive, which allows a much larger timestep to be taken (recall the small timesteps used in Examples 05 and 11). This is exact only for the linearisation about an even equilibrium in an even machine: the plasma cannot move vertically, so it cannot be used for vertical displacement events or asymmetric scenarios. The timestep cannot be arbitrarily large, however: it must still resolve the retained dynamics, keep the linearisation accurate (the Jacobians are rebuilt whenever the plasma has changed significantly), and be small compared with the timescales and gains used in the virtual PCS." ] }, { "cell_type": "code", "execution_count": null, "id": "24", "metadata": {}, "outputs": [], "source": [ "from freegsnke.symmetry_reduced_solve import SymmetryReducedSolver\n", "\n", "# plasma resistivity [Ohm m] (as in Example 11)\n", "plasma_resistivity = 1e-7\n", "\n", "# initialise the solver object\n", "stepping = SymmetryReducedSolver(\n", " eq=eq,\n", " profiles=profiles,\n", " GSStaticSolver=static_solver,\n", " full_timestep=2.5e-3, # <-- 2.5 ms timestep (5x that of Example 11)!\n", " max_internal_timestep=2.5e-3,\n", " plasma_resistivity=plasma_resistivity,\n", " mode_selection=\"coupling\",\n", " fix_n_vessel_modes=30, # <-- 30/69 retained even modes\n", " plasma_descriptor_function=plasma_descriptors,\n", " passive_reflection_operator=passive_reflection_operator,\n", " n_linearization_workers=4,\n", " verbose=False,\n", ")" ] }, { "cell_type": "markdown", "id": "25", "metadata": {}, "source": [ "### Inspect passive-mode parity and truncation\n", "\n", "Open markers show the discarded passive modes (even in blue, odd in orange); filled markers show the even modes retained after parity and mode-count selection (we keep the 30 even modes that couple most strongly to the plasma). The spatial panels show representative even and odd mode current patterns." ] }, { "cell_type": "code", "execution_count": null, "id": "26", "metadata": {}, "outputs": [], "source": [ "normal_modes = stepping.evol_metal_curr.normal_modes\n", "passive_parity = normal_modes.passive_mode_parity\n", "passive_frequency = normal_modes.w_passive\n", "retained_passive = stepping.evol_metal_curr.selected_modes_mask[n_active:]\n", "passive_centres = np.array(\n", " [\n", " [np.mean(element[\"R\"]), np.mean(element[\"Z\"])]\n", " for element in symmetric_machine.passive_coils_data\n", " ]\n", ")\n", "\n", "representative_modes = {\n", " \"even mode\": np.flatnonzero(passive_parity > 0)[0],\n", " \"odd mode\": np.flatnonzero(passive_parity < 0)[0],\n", "}\n", "fig, axes = plt.subplots(1, 3, figsize=(13, 5))\n", "\n", "for parity, label, colour in ((1, \"even\", \"tab:blue\"), (-1, \"odd\", \"tab:orange\")):\n", " parity_mask = (passive_parity == parity) & ~retained_passive\n", " axes[0].scatter(\n", " np.flatnonzero(parity_mask),\n", " passive_frequency[parity_mask],\n", " facecolors=\"none\",\n", " edgecolors=colour,\n", " label=f\"{label}, discarded\",\n", " )\n", "retained_indices = np.flatnonzero(retained_passive)\n", "axes[0].scatter(\n", " retained_indices,\n", " passive_frequency[retained_passive],\n", " color=\"tab:blue\",\n", " label=\"even, retained\",\n", ")\n", "axes[0].set_yscale(\"log\")\n", "axes[0].set_xlabel(\"passive-mode index\")\n", "axes[0].set_ylabel(\"frequency [s$^{-1}$]\")\n", "axes[0].set_title(\"Parity-aware mode selection\")\n", "axes[0].grid(True)\n", "axes[0].legend()\n", "\n", "for axis, (title, mode_index) in zip(axes[1:], representative_modes.items()):\n", " amplitudes = normal_modes.Pmatrix[\n", " n_active:, n_active + mode_index\n", " ]\n", " scale = np.max(np.abs(amplitudes))\n", " points = axis.scatter(\n", " passive_centres[:, 0],\n", " passive_centres[:, 1],\n", " c=amplitudes,\n", " cmap=\"coolwarm\",\n", " vmin=-scale,\n", " vmax=scale,\n", " s=30,\n", " edgecolor=\"k\",\n", " )\n", " axis.axhline(0.0, color=\"0.6\", linewidth=1)\n", " axis.set_aspect(\"equal\")\n", " axis.set_xlabel(\"R [m]\")\n", " axis.set_ylabel(\"Z [m]\")\n", " axis.set_title(title)\n", " fig.colorbar(points, ax=axis, label=\"relative mode current\", shrink=0.6)\n", "\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "27", "metadata": {}, "source": [ "### 6. Run the controlled evolution\n", "\n", "Next, we'll run the simulation with a $2.5\\text{ ms}$ solver step and a $1.25\\text{ ms}$ PCS timestep (Example 11 used $0.5\\text{ ms}$ and $0.25\\text{ ms}$).\n", "\n", "The virtual PCS will return the voltages to be applied to the active coils, which the reduced solver will use to advance the retained metal modes, plasma current, and profile response (and equilibrium!).\n", "\n", "The PCS holds the plasma current at its initial value, ramps $R_x$ inwards and back, sweeps the lower outer strikepoint radius $R_{\\mathrm{sp}}$ out to $1.40\\text{ m}$ (Super-X), and holds `Rin` and `Rout` constant as described in Section 4. The plasma resistivity is set to $10^{-7}\\,\\Omega\\,\\mathrm{m}$, as in Example 11." ] }, { "cell_type": "code", "execution_count": null, "id": "28", "metadata": {}, "outputs": [], "source": [ "# setup and storage\n", "dt = stepping.dt_step\n", "n_steps = int(round((tmax - tmin) / dt)) + 1 # simulate from tmin to tmax\n", "dt_pcs = dt / 2\n", "times = tmin + np.arange(n_steps) * dt\n", "\n", "# keep four equilibrium snapshots, evenly spaced in time, for plotting later\n", "snapshot_indices = np.linspace(0, n_steps - 1, 4).astype(int)\n", "snapshots = {0: stepping.eq1.create_auxiliary_equilibrium()}\n", "\n", "# re-linearisation: the solver re-linearises when the relative change in the toroidal current density\n", "# since the last linearisation reaches this threshold (we store this criterion at every step)\n", "relinearise_threshold = 0.05\n", "relinearise_criterion = np.zeros(n_steps - 1)\n", "\n", "dynamic_currents = np.zeros((len(stepping.vessel_currents_vec), n_steps))\n", "dynamic_ip = np.zeros(n_steps)\n", "dynamic_shape = np.zeros((len(ctrl_targets), n_steps))\n", "dynamic_z = np.zeros(n_steps)\n", "dynamic_limited = np.zeros(n_steps, dtype=bool) # is the plasma limited (not diverted)?\n", "voltages = np.zeros((n_active, n_steps - 1))\n", "step_times = np.zeros(n_steps - 1)\n", "\n", "dynamic_currents[:, 0] = stepping.vessel_currents_vec\n", "dynamic_ip[0] = stepping.profiles1.Ip\n", "dynamic_shape[:, 0] = plasma_descriptors(stepping.eq1)\n", "dynamic_z[0] = stepping.eq1.Zcurrent()\n", "dynamic_limited[0] = bool(stepping.profiles1.flag_limiter)\n", "\n", "ip_hist_prev = 0.0\n", "ip_err_prev = 0.0\n", "shape_error_prev = np.zeros(len(ctrl_targets))\n", "shape_history_prev = np.zeros(len(ctrl_targets))\n", "approved_current_prev = initial_active.copy()\n", "approved_voltage_prev = np.zeros(n_active)" ] }, { "cell_type": "code", "execution_count": null, "id": "29", "metadata": {}, "outputs": [], "source": [ "# simulate!\n", "for index, time_value in enumerate(times[:-1]):\n", "\n", " print(\"-----\")\n", " print(f\"t = {np.round(time_value,5)}s (step {index+1}/{n_steps-1})\")\n", "\n", " result = pcs.calculate_ctrl_voltages(\n", " t=time_value,\n", " dt=dt_pcs,\n", " dt_simulator=dt,\n", " ip_meas=dynamic_ip[index],\n", " ip_hist_prev=ip_hist_prev,\n", " ip_err_prev=ip_err_prev,\n", " T_meas=dynamic_shape[:, index],\n", " T_err_prev=shape_error_prev,\n", " T_hist_prev=shape_history_prev,\n", " I_approved_prev=approved_current_prev,\n", " I_meas=dynamic_currents[:n_active, index],\n", " V_approved_prev=approved_voltage_prev,\n", " zip_meas=dynamic_z[index] * dynamic_ip[index],\n", " zipv_meas=0.0,\n", " active_coil_resists=tokamak.coil_resist[:n_active],\n", " verbose=False,\n", " )\n", " (\n", " approved_voltage,\n", " ip_hist_prev,\n", " ip_err_prev,\n", " shape_error_prev,\n", " shape_history_prev,\n", " approved_current_prev,\n", " active_resistances,\n", " ) = result\n", " voltages[:, index] = approved_voltage\n", " approved_voltage_prev = approved_voltage.copy()\n", "\n", " start = time.perf_counter()\n", " stepping.nlstepper(\n", " plasma_resistivity=plasma_resistivity,\n", " active_voltage_vec=approved_voltage,\n", " # Lao logic adds one dependent closure coefficient to each stored\n", " # array; the evolutive interface accepts the independent values only.\n", " profiles_parameters={\n", " \"alpha\": profiles.alpha[:-1].copy(),\n", " \"beta\": profiles.beta[:-1].copy(),\n", " },\n", " custom_active_coil_resistances=active_resistances,\n", " linear_only=True,\n", " target_relative_tol_currents=1e-2,\n", " target_relative_tol_GS=1e-2,\n", " working_relative_tol_GS=5e-2,\n", " max_solving_iterations=20,\n", " relinearise_threshold=relinearise_threshold,\n", " no_GS=False,\n", " verbose=False,\n", " )\n", " step_times[index] = time.perf_counter() - start\n", " relinearise_criterion[index] = stepping.relinearise_criteria\n", "\n", " dynamic_currents[:, index + 1] = stepping.vessel_currents_vec\n", " dynamic_ip[index + 1] = stepping.profiles1.Ip\n", " dynamic_shape[:, index + 1] = plasma_descriptors(stepping.eq1)\n", " dynamic_z[index + 1] = stepping.eq1.Zcurrent()\n", " dynamic_limited[index + 1] = bool(stepping.profiles1.flag_limiter)\n", " if index + 1 in snapshot_indices:\n", " snapshots[index + 1] = stepping.eq1.create_auxiliary_equilibrium()\n", "\n", " # print some stuff to track solve\n", " print(f\" PLASMA QUANTITIES\")\n", " print(f\" Ip = {np.round(dynamic_ip[index+1]/1000,1)} [kA]\")\n", " print(f\" Shape parameters {ctrl_targets} = {np.round(dynamic_shape[:,index+1],3)}\")\n", " print(f\" Z position = {np.round(dynamic_z[index+1],5)} [m]\")" ] }, { "cell_type": "markdown", "id": "30", "metadata": {}, "source": [ "### 7. Inspect the results\n", "\n", "Below we plot the plasma current, the plasma vertical position $Z_{\\mathrm{current}}$ (held on the midplane by symmetry), and the five shape quantities (`Rin`, `Rout`, `Rx`, `Zx`, and the lower outer strikepoint radius `Rsp`) against their reference targets, followed by the active coil currents and voltages (with the PCS limits), snapshots of the equilibrium as it evolves into the Super-X configuration, and finally the passive structure currents." ] }, { "cell_type": "code", "execution_count": null, "id": "31", "metadata": {}, "outputs": [], "source": [ "t_ms = 1e3 * times\n", "shape_reference = np.array( # reference waveform of each shape target, evaluated at the simulation times\n", " [\n", " np.interp(\n", " times,\n", " pcs.ShapeController.data[target][\"ref\"][\"times\"],\n", " pcs.ShapeController.data[target][\"ref\"][\"vals\"],\n", " )\n", " for target in ctrl_targets\n", " ]\n", ")\n", "t_voltage_ms = 1e3 * times[:-1] # each voltage request is applied from the start of its step\n", "colours = {name: f\"C{index}\" for index, name in enumerate(active_coils)}\n", "\n", "# plasma current, vertical position, and shape: evolved values against their reference targets\n", "ip_reference = np.interp(times, plasma_data[\"ip_ref\"][\"times\"], plasma_data[\"ip_ref\"][\"vals\"])\n", "z_reference = np.interp(times, vertical_data[\"z_ref\"][\"times\"], vertical_data[\"z_ref\"][\"vals\"])\n", "fig, axes = plt.subplots(2, 4, figsize=(15, 6), dpi=80, sharex=True, constrained_layout=True)\n", "ip_axis = axes[0, 0]\n", "z_axis = axes[0, 1]\n", "shape_axes = [axes[0, 2], axes[0, 3], axes[1, 0], axes[1, 1], axes[1, 2]]\n", "axes[1, 3].axis(\"off\") # unused\n", "\n", "ip_axis.plot(t_ms, dynamic_ip / 1e3, color=\"k\", label=\"evolved\")\n", "ip_axis.plot(t_ms, ip_reference / 1e3, color=\"tab:red\", linestyle=\"--\", label=\"reference\")\n", "ip_axis.set_ylabel(r\"Plasma current, $I_p$ [kA]\")\n", "ip_axis.legend()\n", "\n", "z_axis.plot(t_ms, dynamic_z, color=\"k\", label=\"evolved\")\n", "z_axis.plot(t_ms, z_reference, color=\"tab:red\", linestyle=\"--\", label=\"reference\")\n", "z_axis.set_ylabel(r\"Vertical position, $Z$ [m]\")\n", "\n", "for target_index, (axis, target) in enumerate(zip(shape_axes, ctrl_targets)):\n", " axis.plot(t_ms, dynamic_shape[target_index], color=\"k\", label=\"evolved\")\n", " if shape_data[target][\"blend\"][\"vals\"][0] > 0: # the reference of an uncontrolled target is not followed\n", " axis.plot(t_ms, shape_reference[target_index], color=\"tab:red\", linestyle=\"--\", label=\"reference\")\n", " axis.set_ylabel(f\"{target} [m]\")\n", " else:\n", " axis.set_ylabel(f\"{target} [m] (uncontrolled)\")\n", "\n", "for axis in [ip_axis, z_axis] + shape_axes:\n", " axis.grid(alpha=0.5)\n", "for axis in (axes[0, 3], axes[1, 0], axes[1, 1], axes[1, 2]):\n", " axis.tick_params(labelbottom=True)\n", " axis.set_xlabel(\"Time [ms]\")\n", "fig.suptitle(\"Plasma current, vertical position, and shape: evolved against reference\")\n", "plt.show()\n", "\n", "# active coil currents and voltages (solenoid and shape coils are shown separately)\n", "solenoid = active_coils.index(\"Solenoid\")\n", "shape_coil_indices = [index for index in range(n_active) if index != solenoid]\n", "voltage_limits = pf_data[\"coil_voltage_lims\"][\"vals\"][0]\n", "\n", "fig, axes = plt.subplots(2, 3, figsize=(15, 6), dpi=80, sharex=True, constrained_layout=True)\n", "\n", "axes[0, 0].plot(t_ms, dynamic_currents[solenoid] / 1e3, color=colours[\"Solenoid\"], label=\"Solenoid\")\n", "axes[0, 0].axhline(max_current_lims[solenoid] / 1e3, color=\"tab:red\", linestyle=\"--\", linewidth=1, label=\"PCS limits\")\n", "axes[0, 0].axhline(min_current_lims[solenoid] / 1e3, color=\"tab:red\", linestyle=\"--\", linewidth=1)\n", "axes[0, 0].set_ylabel(\"Solenoid current [kA]\")\n", "axes[0, 0].legend()\n", "\n", "axes[1, 0].step(t_voltage_ms, voltages[solenoid], where=\"post\", color=colours[\"Solenoid\"])\n", "axes[1, 0].axhline(voltage_limits[solenoid], color=\"tab:red\", linestyle=\"--\", linewidth=1, label=\"PCS limits\")\n", "axes[1, 0].axhline(-voltage_limits[solenoid], color=\"tab:red\", linestyle=\"--\", linewidth=1)\n", "axes[1, 0].set_ylabel(\"Solenoid voltage [V]\")\n", "axes[1, 0].legend()\n", "\n", "for index in shape_coil_indices:\n", " name = active_coils[index]\n", " axes[0, 1].plot(t_ms, dynamic_currents[index] / 1e3, color=colours[name], label=name)\n", " axes[0, 2].plot(t_ms, (dynamic_currents[index] - dynamic_currents[index, 0]) / 1e3, color=colours[name], label=name)\n", " axes[1, 1].step(t_voltage_ms, voltages[index], where=\"post\", color=colours[name], label=name)\n", " axes[1, 2].step(t_voltage_ms, voltages[index], where=\"post\", color=colours[name], label=name)\n", "axes[1, 1].axhline(voltage_limits[shape_coil_indices[0]], color=\"tab:red\", linestyle=\"--\", linewidth=1)\n", "axes[1, 1].axhline(-voltage_limits[shape_coil_indices[0]], color=\"tab:red\", linestyle=\"--\", linewidth=1)\n", "axes[0, 1].set_ylabel(\"Shape-coil currents [kA]\")\n", "axes[0, 2].set_ylabel(\"Shape-coil current change [kA]\")\n", "axes[1, 1].set_ylabel(\"Shape-coil voltages [V] (limits: dashed)\")\n", "axes[1, 2].set_ylabel(\"Shape-coil voltages [V] (zoom)\")\n", "axes[1, 2].set_ylim(-250, 250)\n", "axes[0, 1].legend(ncol=2, fontsize=\"small\")\n", "\n", "for axis in axes.ravel():\n", " axis.grid(alpha=0.5)\n", "for axis in axes[1]:\n", " axis.set_xlabel(\"Time [ms]\")\n", "fig.suptitle(\"Active coil currents and voltages\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "32", "metadata": {}, "source": [ "The next cell quantifies how closely the controllers follow their references (the shape errors are measured against the reference waveforms, and the initial offsets of a few millimetres in `Rin`, `Rout`, and `Rx` are included), and whether the coil currents and voltages stay within the PCS limits." ] }, { "cell_type": "code", "execution_count": null, "id": "33", "metadata": {}, "outputs": [], "source": [ "# tracking errors against the reference waveforms\n", "ip_error = 100 * np.abs(dynamic_ip - ip_reference) / ip_reference\n", "print(f\"Ip: maximum deviation {np.max(ip_error):.2f}% (final {ip_error[-1]:.2f}%)\")\n", "for target_index, target in enumerate(ctrl_targets):\n", " if shape_data[target][\"blend\"][\"vals\"][0] > 0:\n", " error = np.abs(dynamic_shape[target_index] - shape_reference[target_index])\n", " print(f\"{target}: maximum error {1e3 * np.max(error):.1f} mm, rms {1e3 * np.sqrt(np.mean(error**2)):.1f} mm\")\n", " else:\n", " drift = 1e3 * np.max(np.abs(dynamic_shape[target_index] - dynamic_shape[target_index, 0]))\n", " print(f\"{target} (uncontrolled): drift from the initial value {drift:.1f} mm\")\n", "print(f\"Vertical position of the plasma: maximum |Z| = {np.max(np.abs(dynamic_z)):.1e} m\")\n", "print(f\"Plasma limited at any time: {bool(np.any(dynamic_limited))}\")\n", "\n", "# limits (the metal currents of the active coils are the first n_active entries)\n", "active_currents = dynamic_currents[:n_active]\n", "current_ok = np.all((active_currents >= min_current_lims[:, None]) & (active_currents <= max_current_lims[:, None]))\n", "margin = np.minimum(max_current_lims[:, None] - active_currents, active_currents - min_current_lims[:, None]).min(axis=1)\n", "print(f\"Coil currents within PCS limits: {current_ok} (smallest margin: {active_coils[np.argmin(margin)]}, {margin.min():.0f} A)\")\n", "print(f\"Coil voltages within PCS limits: {bool(np.all(np.abs(voltages) <= voltage_limits[:, None] + 1e-9))}\")\n", "saturated = np.any(np.isclose(np.abs(voltages), voltage_limits[:, None]), axis=1)\n", "print(f\"Coils whose voltage saturates at some time: {[name for name, flag in zip(active_coils, saturated) if flag]}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "34", "metadata": {}, "outputs": [], "source": [ "from matplotlib.lines import Line2D\n", "\n", "# pre-compute outer strikepoints before creating the figure, because\n", "# equilibrium.strikepoints() internally calls plt.contour(...) and plt.close(),\n", "# which would close the active figure if called inside the plotting loop\n", "snapshot_strikepoints = {\n", " index: lower_outer_strikepoint(snapshots[index])\n", " for index in snapshot_indices\n", "}\n", "\n", "# evolution of the equilibrium: four snapshots, evenly spaced in time\n", "fig, axes = plt.subplots(1, 4, figsize=(13, 7), dpi=80, sharex=True, sharey=True, constrained_layout=True)\n", "for axis, index in zip(axes, snapshot_indices):\n", " snapshot = snapshots[index]\n", " snapshot.tokamak.plot(axis=axis, show=False) # plots the active coils and passive structures\n", " snapshot.plot(axis=axis, show=False) # plots the equilibrium and its separatrix\n", " rsp_snap, zsp_snap = snapshot_strikepoints[index]\n", " axis.plot([rsp_snap, rsp_snap], [zsp_snap, -zsp_snap], \"ko\", markersize=5, zorder=5)\n", " axis.set_title(f\"t = {1e3 * times[index]:.0f} ms\")\n", " axis.grid(alpha=0.5)\n", "for axis in axes[1:]:\n", " axis.set_ylabel(\"\")\n", "axes[0].set_xlim(0.1, 2.15)\n", "axes[0].set_ylim(-2.25, 2.25)\n", "axes[-1].legend(\n", " handles=[\n", " Line2D([], [], color=\"r\", label=\"separatrix\"),\n", " Line2D([], [], color=\"r\", marker=\"x\", linestyle=\"\", label=\"X-points\"),\n", " Line2D([], [], color=\"g\", marker=\"2\", linestyle=\"\", label=\"O-point\"),\n", " Line2D([], [], color=\"k\", marker=\"o\", linestyle=\"\", label=\"outer strikepoints\"),\n", " ],\n", " loc=\"lower right\",\n", " fontsize=\"small\",\n", ")\n", "\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "35", "metadata": {}, "outputs": [], "source": [ "# passive structure currents (the passive elements follow the active coils in the stored current vector)\n", "passive_currents = dynamic_currents[n_active:]\n", "passive_names = list(symmetric_machine.passive_names)\n", "upper = np.array([passive_names.index(pair.upper_name) for pair in symmetric_machine.passive_pairs])\n", "lower = np.array([passive_names.index(pair.lower_name) for pair in symmetric_machine.passive_pairs])\n", "passive_centres = np.array([[np.mean(element[\"R\"]), np.mean(element[\"Z\"])] for element in symmetric_machine.passive_coils_data])\n", "scale, unit = (1e-3, \"kA\") if np.max(np.abs(passive_currents)) > 1e3 else (1.0, \"A\")\n", "\n", "fig, (time_axis, space_axis) = plt.subplots(1, 2, figsize=(13, 6), dpi=80, constrained_layout=True)\n", "\n", "# time evolution: reflected partners carry identical currents, so only one element of each pair is drawn\n", "largest = np.argsort(np.max(np.abs(passive_currents[upper]), axis=1))[::-1]\n", "for rank, pair_index in enumerate(largest):\n", " label = passive_names[upper[pair_index]] if rank < 8 else None # label the eight largest only\n", " time_axis.plot(t_ms, scale * passive_currents[upper[pair_index]], linewidth=1, label=label)\n", "time_axis.set_xlabel(\"Time [ms]\")\n", "time_axis.set_ylabel(f\"Passive structure current [{unit}]\")\n", "time_axis.set_title(\"Passive currents (one element per pair; the partners are identical)\")\n", "time_axis.legend(ncol=2, fontsize=\"small\")\n", "time_axis.grid(alpha=0.5)\n", "\n", "# spatial distribution at the end of the simulation\n", "limit = scale * np.max(np.abs(passive_currents[:, -1]))\n", "points = space_axis.scatter(\n", " passive_centres[:, 0],\n", " passive_centres[:, 1],\n", " c=scale * passive_currents[:, -1],\n", " cmap=\"coolwarm\",\n", " vmin=-limit,\n", " vmax=limit,\n", " s=40,\n", " edgecolor=\"k\",\n", " zorder=3,\n", ")\n", "space_axis.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "space_axis.set_aspect(\"equal\")\n", "space_axis.set_xlabel(\"Major radius [m]\")\n", "space_axis.set_ylabel(\"Height [m]\")\n", "space_axis.set_title(f\"Passive currents at t = {t_ms[-1]:.0f} ms\")\n", "space_axis.grid(alpha=0.5)\n", "fig.colorbar(points, ax=space_axis, label=f\"Passive structure current [{unit}]\", shrink=0.6)\n", "plt.show()\n", "\n", "upper_lower_difference = np.max(np.abs(passive_currents[upper] - passive_currents[lower]))\n", "print(f\"Maximum upper/lower passive current difference: {upper_lower_difference:.2e} A\")" ] }, { "cell_type": "markdown", "id": "36", "metadata": {}, "source": [ "The passive structure currents are even in $Z$: each upper element carries exactly the same current as its lower partner. The largest changes occur when the $R_x$ and $R_{\\mathrm{sp}}$ ramps start and end, and the largest currents flow in the vessel, divertor coil cases, and structures closest to the plasma and divertor legs." ] }, { "cell_type": "markdown", "id": "37", "metadata": {}, "source": [ "Finally, we look at the wall-clock time taken by each step of the evolutive solver (this excludes the virtual PCS calculation). The red markers show the steps in which the solver re-linearised, i.e. where the relative change in the toroidal current density since the last linearisation reached the threshold (5%). Re-linearisations are expensive because the Jacobians are rebuilt, and steps where the equilibrium changes rapidly during the $R_x$ and $R_{\\mathrm{sp}}$ ramps also require more Newton-Krylov iterations in the inner Grad-Shafranov solve." ] }, { "cell_type": "code", "execution_count": null, "id": "38", "metadata": {}, "outputs": [], "source": [ "# wall-clock time of each evolutive solver step (the virtual PCS calculation is not included)\n", "median_step = np.median(step_times)\n", "t_step_ms = 1e3 * times[1:] # time at the end of each step\n", "relin_steps = np.flatnonzero(relinearise_criterion >= relinearise_threshold) # steps in which the solver re-linearised\n", "\n", "fig, (step_axis, total_axis) = plt.subplots(1, 2, figsize=(13, 4.5), dpi=80, constrained_layout=True)\n", "\n", "step_axis.semilogy(t_step_ms, step_times, color=\"k\", linewidth=0.8, label=\"all steps\")\n", "step_axis.semilogy(t_step_ms[relin_steps], step_times[relin_steps], \"v\", color=\"tab:red\", markersize=7, label=f\"re-linearisations ({len(relin_steps)})\")\n", "step_axis.axhline(median_step, color=\"tab:blue\", linestyle=\"--\", linewidth=1, label=f\"median step ({1e3 * median_step:.0f} ms)\")\n", "step_axis.set_xlabel(\"Time [ms]\")\n", "step_axis.set_ylabel(\"Wall-clock time per solver step [s]\")\n", "step_axis.set_title(\"Time per step\")\n", "step_axis.legend(loc=\"lower right\")\n", "step_axis.grid(alpha=0.5, which=\"both\")\n", "\n", "total_axis.plot(t_step_ms, np.cumsum(step_times), color=\"k\")\n", "for step in relin_steps:\n", " total_axis.axvline(t_step_ms[step], color=\"tab:red\", linestyle=\":\", linewidth=1)\n", "total_axis.plot([], [], color=\"tab:red\", linestyle=\":\", label=\"re-linearisation\")\n", "total_axis.set_xlabel(\"Simulated time [ms]\")\n", "total_axis.set_ylabel(\"Cumulative wall-clock time [s]\")\n", "total_axis.set_title(f\"Total: {np.sum(step_times):.0f} s for {t_step_ms[-1]:.0f} ms of plasma evolution\")\n", "total_axis.legend()\n", "total_axis.grid(alpha=0.5)\n", "plt.show()\n", "\n", "print(f\"{len(step_times)} steps of {1e3 * dt:.1f} ms | median {1e3 * median_step:.0f} ms | total {np.sum(step_times):.0f} s\")\n", "print(f\"{len(relin_steps)} re-linearisations, at t = {np.round(1e3 * times[relin_steps], 1)} ms\")" ] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }